package com.group9.repository.impl;

import com.group9.dto.PageInfo;
import com.group9.pojo.CommentResponse;
import com.group9.pojo.ResourceComment;
import com.group9.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Lcouncillor on 2020/6/6.
 */
@Repository
public class CommentRepositoryImpl implements CommentRepository {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Integer insertResourceComment(ResourceComment resourceComment) {
        mongoTemplate.save(resourceComment, "resource_comment");
        return 1;
    }

    @Override
    public Integer insertCommentResponse(CommentResponse commentResponse) {
        mongoTemplate.save(commentResponse, "comment_response");
        return 1;
    }

    @Override
    public ResourceComment selectResourceCommentById(String id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(id);
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query, ResourceComment.class, "resource_comment");
    }

    @Override
    public PageInfo selectByResourceIdAndPage(String resourceId, PageInfo pageInfo) {
        Query query = new Query();

        //确定资源id
        Criteria criteria = Criteria.where("resource_id").is(resourceId);
        query.addCriteria(criteria);
        pageInfo.setTotalSize((int) mongoTemplate.count(query,ResourceComment.class,"resource_comment"));

        //分页
        query.skip(pageInfo.getPageNum()).limit(pageInfo.getPageSize());

        //按最新评价排序
        query.with(Sort.by(Sort.Direction.DESC,"comment_time"));

        List<ResourceComment> resourceComments = mongoTemplate.find(query,ResourceComment.class,"resource_comment");
        pageInfo.setDataList(resourceComments);
        return pageInfo;
    }

    @Override
    public Integer updateCommentPic(String id, String commentPicUrl) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = new Update();
        update.addToSet("comment_pic", commentPicUrl);
        mongoTemplate.upsert(query, update, ResourceComment.class,"resource_comment");

        return 1;
    }

    @Override
    public CommentResponse selectCommentResponseById(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query,CommentResponse.class, "comment_response");
    }


}
